
#include "power.h"
#include "common.h"
#include "gsm0710.h"
#include "debug.h"
#include "timer.h"
#include "stm32f10x_init.h"
#include "lwip/sys.h"
#include "stm32f10x_pwr.h"

extern MachineState msState;

static void sendPSC(unsigned char sleep)
{
  unsigned char sleepData[3] = 
  {
    GSM_C_PSC | GSM_CR, 3, 8
  };
  unsigned char wakeupData[3] = 
  {
    GSM_C_PSC | GSM_CR, 3, 1
  };

  write_frame(0, sleep ? sleepData : wakeupData, 3, GSM_UIH);
}

extern vu32 SystemTick;

void PowerDown(void* none)
{
  DebugPrintf(DEBUG_LEVEL_INFO, "Timeout: PowerDown\r\n");
  SetFlag(GlobalFlag, FLAG_POWERDOWN);
}

void EnterPowerDown()
{
  u32 rtcCounter = 0;
  DebugPrintf(DEBUG_LEVEL_MSG, "EnterPowerDown\r\n");

  while(1)
  {
    IWDG_ReloadCounter();
    RTC_SetAlarm(RTC_GetCounter() + RTC_ALARM);
    RTC_WaitForLastTask();
    DebugPrintf(DEBUG_LEVEL_DETAIL, "Power Down Now.\r\n");
    sendPSC(1);
    SysTick_ITConfig(DISABLE);
    rtcCounter = RTC_GetCounter();
    if (CheckFlag(GlobalFlag, /*FLAG_GPRS*/FLAG_FLASH))
      TIM_Cmd(TIM2, DISABLE);

    IWDG_ReloadCounter();

    __WFI();

    IWDG_ReloadCounter();
    SystemTick += (RTC_GetCounter() - rtcCounter) * 1000;
    RTC_SetCounter(0x0);
    RTC_WaitForLastTask();
    CheckTimeOut();

    if (!CheckFlag(GlobalFlag, FLAG_ALARM) || (msState == msReset))
    {
      SysTick_ITConfig(ENABLE);
      if (CheckFlag(GlobalFlag, /*FLAG_GPRS*/FLAG_FLASH))
        TIM_Cmd(TIM2, ENABLE);
      DebugPrintf(DEBUG_LEVEL_INFO, "Power Up By Interrupt.\r\n");
      sendPSC(0);
      ResetFlag(GlobalFlag, FLAG_POWERDOWN);
      break;
    }
    DebugPrintf(DEBUG_LEVEL_DETAIL, "Power Up By Alarm.\r\n");
    ResetFlag(GlobalFlag, FLAG_ALARM);    
  }
}
